package com.green.common;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.green.common.util.StringUtil;

public class UrlUtil {
	private final static String HTML_URL_PREFIX="http://";
	private final static String HTML_URL_HOST_REGEX=HTML_URL_PREFIX+"(.+?)/.+";
	
    public static String getHtmlUrlHost(String htmlUrl){
    	if(StringUtil.isEmpty(htmlUrl)){
    		return null;
    	}
    	final String url=htmlUrl.trim();
    	if(!url.startsWith(HTML_URL_PREFIX)){
    		return null;
    	}
    	
       final Pattern p=Pattern.compile(HTML_URL_HOST_REGEX);
       final Matcher m=p.matcher(url);
       if(m.find()){
    	   return m.group(1);
       }
       return null;
    }
    
    public static String replaceHtmlUrlHost(String htmlUrl,String targetHost){
    	final String host=getHtmlUrlHost(htmlUrl);
    	if(host==null){
    		return htmlUrl;
    	}
    	return htmlUrl.replaceFirst(host, targetHost);
    }
   
}
